package com.railway.switchs.action.authority;

import com.railway.switchs.aspect.OperationLog;
import com.railway.switchs.base.BaseResponse;
import com.railway.switchs.constant.SystemConstant;
import com.railway.switchs.domain.dto.authority.AuthorityPermission;
import com.railway.switchs.domain.dto.authority.AuthorityRolePermission;
import com.railway.switchs.domain.query.authority.AuthorityPermissionQuery;
import com.railway.switchs.domain.query.authority.AuthorityRolePermissionQuery;
import com.railway.switchs.domain.response.AuthorityPermissionResponse;
import com.railway.switchs.enums.EnumOperatorBillType;
import com.railway.switchs.enums.EnumReturnResult;
import com.railway.switchs.service.authority.IAuthorityPermissionService;
import com.railway.switchs.service.authority.IAuthorityRolePermissionService;
import com.railway.switchs.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;


/**
 * @ClassName PermissionAction
 * @Author 魏梓晟
 * @Version 1.0
 **/
@Controller
@Slf4j
@RequestMapping("/back/permission")
public class PermissionAction {

    @Autowired
    private IAuthorityPermissionService authorityPermissionService;

    @Autowired
    private IAuthorityRolePermissionService authorityRolePermissionService;

    /**
     * 进入资源列表页面
     * @return
     */
    @RequestMapping(value = "/list",method = RequestMethod.GET)
    public String list(){
        return "permission/list";
    }

    /**
     * 获取资源数据
     * @param query
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getList",method = RequestMethod.POST)
    public AuthorityPermissionQuery getList(AuthorityPermissionQuery query){
        try{
            query = authorityPermissionService.query(query);
            query.setCode(EnumReturnResult.RETURN_200.getCode());
        }catch (Exception e){
            log.error("获取资源列表数据异常", e);
            query.setCode(EnumReturnResult.RETURN_404.getCode());
            query.setMsg("获取资源数据异常");
        }
        return query;
    }

    /**
     * 进入新增页面
     * @return
     */
    @RequestMapping(value = "/add",method = RequestMethod.GET)
    public String preAdd(){
        return "permission/add";
    }

    /**
     * 新增资源
     * @param authorityPermission
     * @param result
     * @return
     */
    @ResponseBody
    @OperationLog(billType ="2",actionType ="0" )
    @RequestMapping(value = "/add",method = RequestMethod.POST)
    public BaseResponse add(@Validated AuthorityPermission authorityPermission, BindingResult result) {
        BaseResponse response = new BaseResponse();
        try {
            if(result.hasErrors()){
                response.setCode(EnumReturnResult.RETURN_404.getCode());
                response.setMsg("AuthorityPermission-add参数有误");
                log.info("AuthorityPermission-add参数有误："+result.getAllErrors().toString());
                return response;
            }
            //校验资源代码是否唯一
            if(checkUniquePermissionCode(authorityPermission.getPermissionCode())){
                response.setCode(EnumReturnResult.RETURN_404.getCode());
                response.setMsg("该资源代码已存在");
                return response;
            }
            authorityPermissionService.add(authorityPermission);
            response.setCode(EnumReturnResult.RETURN_200.getCode());
            response.setMsg("新增资源成功");
        } catch (Exception e) {
            log.error("新增资源异常",e);
            response.setCode(EnumReturnResult.RETURN_404.getCode());
            response.setMsg("新增资源失败");
        }
        return response;
    }

    /**
     * 进入资源信息修改页面
     * @param id
     * @return
     */
    @RequestMapping(value = "/edit",method = RequestMethod.GET)
    public ModelAndView preEdit(Long id){
        ModelAndView mav = new ModelAndView();
        try{
            AuthorityPermission authorityPermission = authorityPermissionService.get(id);
            mav.addObject("authorityPermission",authorityPermission);
            mav.setViewName("permission/edit");
        }catch (Exception e){
            log.error("获取资源详情失败",e);
            mav.addObject(SystemConstant.ERROR_KEY,"系统异常");
            mav.setViewName("permission/list");
        }
        return mav;
    }

    /**
     * 修改资源信息
     * @param authorityPermission
     * @param result
     * @return
     */
    @ResponseBody
    @OperationLog(billType ="2",actionType ="1" )
    @RequestMapping(value = "/edit",method = RequestMethod.POST)
    public BaseResponse edit(@Validated AuthorityPermission authorityPermission, BindingResult result) {
        BaseResponse response = new BaseResponse();
        try {
            if(result.hasErrors()){
                response.setCode(EnumReturnResult.RETURN_404.getCode());
                response.setMsg("AuthorityPermission-edit参数有误");
                log.info("AuthorityPermission-edit参数有误："+result.getAllErrors().toString());
                return response;
            }
            AuthorityPermission authorityPermissionTemp = authorityPermissionService.get(authorityPermission.getId());
            //校验资源代码是否唯一
            if(!authorityPermissionTemp.getPermissionCode().equals(authorityPermission.getPermissionCode())){
                response.setCode(EnumReturnResult.RETURN_404.getCode());
                response.setMsg("资源代码不允许修改");
                return response;
            }
            authorityPermissionService.edit(authorityPermission);
            response.setCode(EnumReturnResult.RETURN_200.getCode());
            response.setMsg("修改资源成功");
        } catch (Exception e) {
            log.error("修改资源异常",e);
            response.setCode(EnumReturnResult.RETURN_404.getCode());
            response.setMsg("修改资源失败");
        }
        return response;
    }

    /**
     * 删除资源
     * @param id
     * @return
     */
    @ResponseBody
    @OperationLog(billType ="2",actionType ="2" )
    @RequestMapping(value = "/delete",method = RequestMethod.POST)
    public BaseResponse delete(Long id){
        BaseResponse response = new BaseResponse();
        try{
            //删除资源的同时删除资源被授权信息
            AuthorityPermission authorityPermission = authorityPermissionService.get(id);
            AuthorityRolePermissionQuery authorityRolePermissionQuery = new AuthorityRolePermissionQuery();
            authorityRolePermissionQuery.setPermissionCode(authorityPermission.getPermissionCode());
            List<AuthorityRolePermission> authorityRolePermissions = authorityRolePermissionService.getList(authorityRolePermissionQuery);
            if(StringUtil.isNotEmpty(authorityRolePermissions)){
                for(AuthorityRolePermission authorityRolePermission : authorityRolePermissions){
                    authorityRolePermissionService.delete(authorityRolePermission.getId());
                }
            }
            authorityPermissionService.delete(id);
            response.setCode(EnumReturnResult.RETURN_200.getCode());
            response.setMsg("删除资源成功");
        }catch (Exception e){
            log.error("删除资源异常",e);
            response.setCode(EnumReturnResult.RETURN_404.getCode());
            response.setMsg("删除资源失败");
        }
        return response;
    }

    /**
     * 获取授权列表所需数据
     * @param query
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getAuthorizeData",method = RequestMethod.POST)
    public AuthorityPermissionResponse getAuthorizeData(AuthorityPermissionQuery query){
        AuthorityPermissionResponse response = new AuthorityPermissionResponse();
        try{
            List<AuthorityPermission> authorityPermissionList = authorityPermissionService.getLevelList(query);
            response.setData(authorityPermissionList);
            response.setCode(EnumReturnResult.RETURN_200.getCode());
        }catch (Exception e){
            log.error("获取资源异常",e);
            response.setCode(EnumReturnResult.RETURN_404.getCode());
            response.setMsg("获取资源失败");
        }
        return response;
    }

    /**
     * 校验是否已存在permissionCode
     * @param permissionCode
     * @return
     */
    private boolean checkUniquePermissionCode(String permissionCode) {
        AuthorityPermissionQuery query = new AuthorityPermissionQuery();
        query.setPermissionCode(permissionCode);
        List<AuthorityPermission> authorityPermissionList = authorityPermissionService.getList(query);
        if(StringUtil.isEmpty(authorityPermissionList)){
            return false;
        }
        return true;
    }

}
